package com.qingcheng.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qingcheng.dao.*;
import com.qingcheng.entity.PageResult;
import com.qingcheng.pojo.goods.*;
import com.qingcheng.service.goods.SpuService;
import com.qingcheng.util.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SpuService.class)
public class SpuServiceImpl implements SpuService {

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private BrandCategoryMapper brandCategoryMapper;

    @Autowired
    private StatusMapper statusMapper;

    @Autowired
    private LogMapper logMapper;

    /**
     * 返回全部记录
     *
     * @return
     */
    public List<Spu> findAll() {
        return spuMapper.selectAll();
    }

    /**
     * 分页查询
     *
     * @param page 页码
     * @param size 每页记录数
     * @return 分页结果
     */
    public PageResult<Spu> findPage(int page, int size) {
        PageHelper.startPage(page, size);
        Page<Spu> spus = (Page<Spu>) spuMapper.selectAll();
        return new PageResult<Spu>(spus.getTotal(), spus.getResult());
    }

    /**
     * 条件查询
     *
     * @param searchMap 查询条件
     * @return
     */
    public List<Spu> findList(Map<String, Object> searchMap) {

        //不完善， 待改进      数据isDelete为1的商品不应该显示
        Example example = createExample(searchMap);
        return spuMapper.selectByExample(example);
    }

    /**
     * 分页+条件查询
     *
     * @param searchMap
     * @param page
     * @param size
     * @return
     */
    public PageResult<Spu> findPage(Map<String, Object> searchMap, int page, int size) {
        PageHelper.startPage(page, size);
        Example example = createExample(searchMap);
        Page<Spu> spus = (Page<Spu>) spuMapper.selectByExample(example);
        return new PageResult<Spu>(spus.getTotal(), spus.getResult());
    }

    /**
     * 根据Id查询
     *
     * @param id
     * @return
     */
    public Spu findById(String id) {
        return spuMapper.selectByPrimaryKey(id);
    }

    /**
     * 新增
     *
     * @param spu
     */
    public void add(Spu spu) {
        spuMapper.insert(spu);
    }

    /**
     * 修改
     *
     * @param spu
     */
    public void update(Spu spu) {
        spuMapper.updateByPrimaryKeySelective(spu);
    }


    /**
     * 添加商品
     *
     * @param goods
     */
    @Override
    @Transactional
    public void addGoods(Goods goods) {
        //添加商品信息
        Spu spu = goods.getSpu();

        if (spu.getId() == null || "".equals(spu.getId())) {
            //设置商品id,理论上全球唯一
            spu.setId(idWorker.nextId() + "");

            spuMapper.insert(spu);

        } else {

            //删除原来的sku
            Example example = new Example(Sku.class);

            Example.Criteria criteria = example.createCriteria();

            criteria.andEqualTo("spuId", spu.getId());

            skuMapper.deleteByExample(example);

            //修改spu

            spuMapper.updateByPrimaryKey(spu);

        }


        CategoryBrand categoryBrand = new CategoryBrand();

        categoryBrand.setBrandId(spu.getBrandId());

        categoryBrand.setCategoryId(spu.getCategory3Id());

        int count = brandCategoryMapper.selectCount(categoryBrand);

        if (count == 0) {

            brandCategoryMapper.insert(categoryBrand);

        }

        //获取Data时间用于设置商品修改属性
        Date date = new Date();

        //根据id获取对应的品牌名
        Brand brand = brandMapper.selectByPrimaryKey(spu.getBrandId());

        //根据id获取对应的分类名
        Category category = categoryMapper.selectByPrimaryKey(spu.getCategory3Id());


        /**
         *
         * 设置浏览器未传递的属性
         *
         * */

        //添加商品属性
        List<Sku> skuList = goods.getSkuList();
        for (Sku sku : skuList) {

            //判断sku是否为null如果为null则是新增，如果不为null则是修改
            if (sku.getId() == null) {

                //设置属性id
                sku.setId(idWorker.nextId() + "");
                //设置创建时间
                sku.setCreateTime(date);


            }
            //没有规格的sku

            if (sku.getSpec() == null || "".equals(sku.getSpec())) {

                sku.setSpec("{}");

            }


            /*设置sku的name值   = spu名称+规格值列表 */
            String name = spu.getName();
            //
            Map<String, String> map = JSON.parseObject(sku.getSpec(), Map.class);

            for (String value : map.values()) {

                name += " " + value;

            }
            //设置名称
            sku.setName(name);
            //设置分类id
            sku.setSpuId(spu.getId());

            if (brand != null) {
                //设置品牌名
                sku.setBrandName(brand.getName());
            }

            //设置修改时间
            sku.setUpdateTime(date);
            //设置三级分类的ID
            sku.setCategoryId(category.getId());
            //设置三级分类的名称
            sku.setCategoryName(category.getName());
            //评论数
            sku.setCommentNum(0);
            //销量数
            sku.setSaleNum(0);

            //调用添加方法
            skuMapper.insert(sku);
        }


    }

    @Override
    public Goods findByGoods(String spuId) {
        Goods goods = new Goods();

        Spu spu = spuMapper.selectByPrimaryKey(spuId);
        goods.setSpu(spu);


        //创建查询对象,并传入对应实体类class文件
        Example example = new Example(Sku.class);
        Example.Criteria criteria = example.createCriteria();
        //调用方法传递参数
        criteria.andEqualTo("spuId", spuId);

        //调用通用mapper提供的字段查询方法
        List<Sku> skus = skuMapper.selectByExample(example);

        //设置参数
        goods.setSkuList(skus);


        return goods;
    }

    @Override
    public void audit(String id, String status, String message) {

        //创建spu
        Spu spu = new Spu();


        Status status1 = new Status();
        status1.setId(id);
        Log log = new Log();
        log.setSpuId(id);
        Date date = new Date();
        //设置状态
        spu.setStatus(status);
        if ("1".equals(status)) {
            spu.setIsMarketable("1"); //审核通过上架
            //审核通过
            Status status2 = statusMapper.selectOne(status1);
            if (status2 == null) {
                status1.setId(idWorker.nextId() + "");
                status1.setMessage(date + ":" + id + ",审核通过:" + message + "\n");
                status1.setSpuId(id);
                statusMapper.insert(status1);

            } else {


                status2.setMessage( status2.getMessage()+date + ":" + id + "原因:" + message + "\n");


                statusMapper.updateByPrimaryKey(status2);
            }

            //审核日志

            Log log1 = logMapper.selectOne(log);
            if (log1==null){
                log.setId(idWorker.nextId()+"");
                log.setLog(date+":"+"商品被审核并通过审核,商品编号:"+id+"\n");
                log.setSpuId(id);
                logMapper.insert(log);
            }else {

                log1.setLog(log1.getLog()+date+":"+"商品被审核并通过审核,商品编号:"+id+"\n");

                logMapper.updateByPrimaryKey(log1);
            }


        }


        //记录商品审核记录/ 审核未通过
        if ("2".equals(status)) {

            Status status2 = statusMapper.selectOne(status1);
            if (status2 == null) {
                status1.setId(idWorker.nextId() + "");
                status1.setMessage(date + ":" + id + "审核未通过,原因:" + message + "\n");
                status1.setSpuId(id);
                statusMapper.insert(status1);

            } else {
                String message1 = status2.getMessage();

                status2.setMessage(message1+date + ":" + id + "审核未通过,原因:" + message + "\n");


                statusMapper.updateByPrimaryKey(status2);
            }

            //审核日志
            log.setSpuId(id);
            Log log1 = logMapper.selectOne(log);
            if (log1==null){
                log.setId(idWorker.nextId()+"");
                log.setLog(date+":"+"商品被审核但是失败了,商品编号:"+id+"原因:"+message+"\n");
                log.setSpuId(id);
                logMapper.insert(log);
            }else {

                log1.setLog(log1.getLog()+date+":"+"商品被审核但是失败了,商品编号:"+id+"原因:"+message+"\n");

                logMapper.updateByPrimaryKey(log1);
            }



        }


        spuMapper.updateByPrimaryKey(spu);

    }

    /**
     * 商品下架
     *
     * @param id
     */
    @Override
    public void pull(String id) {
        Spu spu = new Spu();

        spu.setId(id);

        spu.setIsMarketable("0");

        Date date = new Date();
        Log log = new Log();
        log.setSpuId(id);
        Log log1 = logMapper.selectOne(log);
        if (log1==null){

            log.setId(idWorker.nextId()+"");

            log.setSpuId(id);

            log.setLog(date+":"+"商品下架:商品id:"+id+"\n");

            logMapper.insert(log);

        }else {

            log1.setLog(log1.getLog()+":"+"商品下架:商品id:"+id+"\n");

            logMapper.updateByPrimaryKey(log1);
        }


        spuMapper.updateByPrimaryKey(spu);


    }

    /**
     * 商品上架
     *
     * @param id
     */
    @Override
    public void put(String id) {

        Spu spu = spuMapper.selectByPrimaryKey(id);

        //上架前判断审核是否通过
        if (!"1".equals(spu.getStatus())) {
            Date date = new Date();
            Log log = new Log();

            log.setSpuId(id);
            Log log1 = logMapper.selectOne(log);
            if (log1==null){

                log.setId(idWorker.nextId()+"");

                log.setSpuId(id);

                log.setLog(date+":"+"商品上架失败,原因商品审核未通过:商品id:"+id+"\n");

                logMapper.insert(log);

            }else {

                log1.setLog(log1.getLog()+":"+"商品上架失败,原因商品审核未通过:商品id:"+id+"\n");

                logMapper.updateByPrimaryKey(log1);
            }



            throw new RuntimeException("商品未通过审核");
        }





        spu.setIsMarketable("1");

        spuMapper.updateByPrimaryKeySelective(spu);


    }

    /**
     * 批量下架
     *
     * @param ids
     * @return
     */
    @Override
    public int pullMany(String[] ids) {

        Spu spu = new Spu();

        spu.setIsMarketable("0");

        Example example = new Example(Spu.class);

        Example.Criteria criteria = example.createCriteria();

        criteria.andIn("id", Arrays.asList(ids));

        //商品日志不会










        int i = spuMapper.updateByExampleSelective(spu, example);

        return i;
    }

    /**
     * 批量上架
     *
     * @param ids
     */
    public int putMany(String[] ids) {

        //修改状态
        Spu spu = new Spu();

        spu.setIsMarketable("1");

        Example example = new Example(Spu.class);

        Example.Criteria criteria = example.createCriteria();

        criteria.andIn("id", Arrays.asList(ids));

        criteria.andEqualTo("isMarketable", "0");

        criteria.andEqualTo("status", "1");

        int updateInt = spuMapper.updateByExampleSelective(spu, example);

        //修改商品日志


        return updateInt;
    }

    /**
     * 将商品加入回收站
     *
     * @param id
     */
    @Override
    public void delete(String id) {

        Spu spu = new Spu();

        spu.setId(id);

        Spu spu1 = spuMapper.selectByPrimaryKey(spu.getId());

        if (spu1 == null) {

            throw new RuntimeException("上架中的商品无法删除");

        }
        spu.setIsDelete("1");

        spuMapper.updateByPrimaryKeySelective(spu);

    }

    /**
     * 显示回收站所有商品
     *
     * @return
     */
    @Override
    public List<Spu> SpuRecycleFindAll() {

        Spu spu = new Spu();

        spu.setIsDelete("1");


        List<Spu> spuList = spuMapper.select(spu);


        return spuList;
    }


    /**
     * 批量加入回收站
     *
     * @param ids
     */
    @Override
    public void deleteSpuMany(String[] ids) {

        //修改状态
        Spu spu = new Spu();

        spu.setIsDelete("1");

        Example example = new Example(Spu.class);

        Example.Criteria criteria = example.createCriteria();

        criteria.andIn("id", Arrays.asList(ids));

        spuMapper.updateByExampleSelective(spu, example);

    }

    /**
     * 删除回收站商品
     *
     * @param id
     */
    @Override
    public void deleteRecycleSpu(String id) {

        spuMapper.deleteByPrimaryKey(id);


    }

    /**
     * 批量删除回收站商品
     *
     * @param ids
     */
    @Override
    public void deleteRecycleSpuMany(String[] ids) {
        //修改状态

        Example example = new Example(Spu.class);

        Example.Criteria criteria = example.createCriteria();

        criteria.andIn("id", Arrays.asList(ids));

        spuMapper.deleteByExample(example);

    }

    /**
     * 商品回收
     *
     * @param id
     */
    @Override
    public void spuRecycle(String id) {

        Spu spu = new Spu();

        spu.setId(id);

        spu.setIsDelete("0");

        spuMapper.updateByPrimaryKeySelective(spu);


    }


    /**
     * 构建查询条件
     *
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap) {
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        if (searchMap != null) {
            // 主键
            if (searchMap.get("id") != null && !"".equals(searchMap.get("id"))) {
                criteria.andLike("id", "%" + searchMap.get("id") + "%");
            }
            // 货号
            if (searchMap.get("sn") != null && !"".equals(searchMap.get("sn"))) {
                criteria.andLike("sn", "%" + searchMap.get("sn") + "%");
            }
            // SPU名
            if (searchMap.get("name") != null && !"".equals(searchMap.get("name"))) {
                criteria.andLike("name", "%" + searchMap.get("name") + "%");
            }
            // 副标题
            if (searchMap.get("caption") != null && !"".equals(searchMap.get("caption"))) {
                criteria.andLike("caption", "%" + searchMap.get("caption") + "%");
            }
            // 图片
            if (searchMap.get("image") != null && !"".equals(searchMap.get("image"))) {
                criteria.andLike("image", "%" + searchMap.get("image") + "%");
            }
            // 图片列表
            if (searchMap.get("images") != null && !"".equals(searchMap.get("images"))) {
                criteria.andLike("images", "%" + searchMap.get("images") + "%");
            }
            // 售后服务
            if (searchMap.get("saleService") != null && !"".equals(searchMap.get("saleService"))) {
                criteria.andLike("saleService", "%" + searchMap.get("saleService") + "%");
            }
            // 介绍
            if (searchMap.get("introduction") != null && !"".equals(searchMap.get("introduction"))) {
                criteria.andLike("introduction", "%" + searchMap.get("introduction") + "%");
            }
            // 规格列表
            if (searchMap.get("specItems") != null && !"".equals(searchMap.get("specItems"))) {
                criteria.andLike("specItems", "%" + searchMap.get("specItems") + "%");
            }
            // 参数列表
            if (searchMap.get("paraItems") != null && !"".equals(searchMap.get("paraItems"))) {
                criteria.andLike("paraItems", "%" + searchMap.get("paraItems") + "%");
            }
            // 是否上架
            if (searchMap.get("isMarketable") != null && !"".equals(searchMap.get("isMarketable"))) {
                criteria.andLike("isMarketable", "%" + searchMap.get("isMarketable") + "%");
            }
            // 是否启用规格
            if (searchMap.get("isEnableSpec") != null && !"".equals(searchMap.get("isEnableSpec"))) {
                criteria.andLike("isEnableSpec", "%" + searchMap.get("isEnableSpec") + "%");
            }
            // 是否删除
            if (searchMap.get("isDelete") != null && !"".equals(searchMap.get("isDelete"))) {
                criteria.andLike("isDelete", "%" + searchMap.get("isDelete") + "%");
            }
            // 审核状态
            if (searchMap.get("status") != null && !"".equals(searchMap.get("status"))) {
                criteria.andLike("status", "%" + searchMap.get("status") + "%");
            }

            // 品牌ID
            if (searchMap.get("brandId") != null) {
                criteria.andEqualTo("brandId", searchMap.get("brandId"));
            }
            // 一级分类
            if (searchMap.get("category1Id") != null) {
                criteria.andEqualTo("category1Id", searchMap.get("category1Id"));
            }
            // 二级分类
            if (searchMap.get("category2Id") != null) {
                criteria.andEqualTo("category2Id", searchMap.get("category2Id"));
            }
            // 三级分类
            if (searchMap.get("category3Id") != null) {
                criteria.andEqualTo("category3Id", searchMap.get("category3Id"));
            }
            // 模板ID
            if (searchMap.get("templateId") != null) {
                criteria.andEqualTo("templateId", searchMap.get("templateId"));
            }
            // 运费模板id
            if (searchMap.get("freightId") != null) {
                criteria.andEqualTo("freightId", searchMap.get("freightId"));
            }
            // 销量
            if (searchMap.get("saleNum") != null) {
                criteria.andEqualTo("saleNum", searchMap.get("saleNum"));
            }
            // 评论数
            if (searchMap.get("commentNum") != null) {
                criteria.andEqualTo("commentNum", searchMap.get("commentNum"));
            }

        }
        return example;
    }

}
